package com.shuimin.as.service;

import pond.common.S;
import pond.web.EndToEndException;
import pond.web.Session;
import pond.web.WSCtx;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by edwin on 2/25/2017.
 */
public class NotificationService {

    private final static Map<Session, List<WSCtx>> ctxHolder = new ConcurrentHashMap<>();


    public static void add(Session session, WSCtx wsCtx) {
        List<WSCtx> list = ctxHolder.computeIfAbsent(session, k -> new LinkedList<>());
        list.add(wsCtx);
        S.echo("ctxHolder",ctxHolder);
    }

    public static void notifyAll(Session session, NotificationEvent event) {
        List<WSCtx> wsCtxs = ctxHolder.get(session);
        if(wsCtxs == null){
            throw new EndToEndException(500, "Can't find ctx to notifyAll, session-id:" + session.id());
        }
        S._for(wsCtxs).each(wsCtx -> wsCtx.sendTextFrame(event.toJSON()));
    }

}
